<template>
    <view class="container">
        <header-bar :config="config"></header-bar>
        <view class="basic-info">
            <view class="title">基础信息</view>
            <view class="choose" @click="selectClient">
                <view class="flex-v-c">选择会员</view>
                <view class="flex-main" :class="{ color3: !client }"><text class="text-show-line-1">{{ client ?
                    client : "请选择会员"
                        }}</text>
                    <uni-icons type="arrowright" size="30" customIcons="icon-black"></uni-icons>
                </view>
            </view>
        </view>
        <view class="product-head">
            <view class="title">商品清单</view>
            <view class="btn" @click="addpro"><uni-icons size="24" type="plusempty"></uni-icons>添加商品</view>
        </view>


        <view class="action-bar" v-if="!isEdit">
            <view class="total">共{{ total.totalNum }}件</view>
            <view v-if="carList.length" class="edit" @click="edit(true)">编辑</view>
        </view>
        <view class="action-bar" v-else>
            <view v-if="carList.length" style="display: flex;">
                <checkbox-group @change="checkboxChange">
                    <label class="item-radio custom-checkbox-box">
                        <checkbox class="checkbox-mark" :checked="isSelectAllFn(selectData)" value="all"></checkbox>
                        <custom-checkbox :isSelect="isSelectAllFn(selectData)"></custom-checkbox>
                        <text class="text">全选</text>
                    </label>
                </checkbox-group>
            </view>
            <view class="edit" @click="edit(false)">退出编辑</view>
        </view>

        <!-- 添加商品列表 -->
        <!-- :height="listHeight" :style="'height:' + (systemInfo.windowHeight - 100) + 'px'" -->
        <view class="main">
            <scroll-view :style="'height:' + listHeight" scroll-y="true">
                <view class="product-list" v-if="carList.length">
                    <view v-for="(item, index) in carList" :key="index" class="product-list-item">
                        <view class="product-main">
                            <label v-if="isEdit" class="item-radio" @click.stop="change(item)">
                                <custom-checkbox :isSelect="item.isSelect"></custom-checkbox>
                            </label>
                            <view class="product-main-left">
                                <image class="product-item-img"
                                    :src="item.V_ThumbnailUrl160 ? easyGetImgUrl(item.V_ThumbnailUrl160) : '/static/img/no-img.jpg'">
                                </image>
                            </view>
                            <view class="product-main-right">
                                <view class="name">{{ item.V_Title }}</view>
                                <view class="no">货号:{{ item.SkuCode }}</view>
                                <view class="spec">{{ item.V_AttributeNameValue }}</view>
                                <view class="workerPrice">成本价：{{ item.WorkerPrice }}</view>
                                <view class="price-group">
                                    <view class="price1">¥{{ item.V_GradePrice }} / x{{ item.Amount }}{{ item.UnitName ?
                                        item.UnitName : item.RationUnit }}
                                        <text v-if="isEdit" class="edit" @click="editPrcie(item)">修改</text>
                                    </view>
                                </view>
                            </view>
                        </view>
                    </view>
                </view>
                <view class="main mescroll-empty" v-else>
                    <image src="/static/img/empty.png"></image>
                    <view>请添加商品</view>
                </view>
            </scroll-view>
        </view>

        <!-- 底部 -->
        <view class="bottom-bar" v-if="isEdit">
            <button class="btn btn-main" @click="save">保存</button>
        </view>


        <!-- 修改运费 -->
        <uni-popup ref="priceEdit" type="center" :animation="false" :mask-click="false">
            <view class="pop-return-box">
                <view class="pop-return-li">
                    <view>成&nbsp;本&nbsp;价：</view>
                    <view class="workerPrice">{{ workerPrice }}</view>
                </view>
                <view class="pop-return-li">
                    <view>单&nbsp;&nbsp;&nbsp;&nbsp;价：</view>
                    <input type="digit" v-model="changePriceMoney" @input="keyPostPriceAmount($event)" />
                </view>
                <view class="pop-action">
                    <view @click="priceEditClose">取消</view>
                    <view @click="priceEditConfirm">确定</view>
                </view>
            </view>
        </uni-popup>
    </view>
</template>

<script>
import { mapMutations, mapState, mapGetters } from "vuex"
import { GetCarList, GetUserAddressList } from "@/service/api/user.js"
import { getElementHeight } from "@/uni-sub-base/utils/elementUtil.js"
import customCheckbox from "@/components/common/custom-checkbox.vue"
import { deleteRefundOrderTemp, getTempCartTotal, getCarList } from "@/utils/valetCartUtil.js"
import { SaveProductPrice, DeleteProductSkuPrice } from "@/service/api/product.js"
export default {
    components: {
        customCheckbox
    },
    watch: {
        getValetCartData(e) {
            this.getTotal()
            this.$forceUpdate()
        },
    },
    data() {
        return {
            placeholderText: "输入会员名称或商品名称",
            config: {
                title: "新增记录",
                centerSlot: true,
                // rightSlot: true,
                rightBtns: [],
                backPage: "/pages/private/index",
            },
            listHeight: "",
            loadOk: false,
            refresh: false,
            client: "",
            valetUserId: 0,
            valetUserInfo: "",
            storeUserId: 0,
            carList: [],
            carGift: [],
            warehouseId: "",
            isEdit: false,
            isShowCheckBox: true,
            total: {
                totalNum: 0,
                totalPrice: 0,
                class: 0,
            },
            curEditPriceItem: {}, // 当前修改价格商品
            selectData: [],
            selectType: 4,
            workerPrice: 0,
            changePriceMoney: 0
        }
    },
    computed: {
        ...mapGetters(["getUpOrderView", "getValetCartData"]),
    },
    created() {
        this.config.backgroundColor = [1, "#FFF2F0"]
    },
    onLoad(e) {
        this.selectType = e.selectType
        if (e.valetUserInfo) {
            this.valetUserInfo = JSON.parse(decodeURIComponent(e.valetUserInfo))
            this.valetUserId = Number(e.valetUserId)
            this.client = this.valetUserInfo.StoreName
            this.storeUserId = this.valetUserInfo.StoreUserId
        }
    },
    mounted() {
        this.getListHeight()
    },
    onShow() {
        this.carlist()
        this.getTotal()
        getCarList(this.valetUserId, this.warehouseId, -1).then((res) => {
            this.$forceUpdate()
        })
    },
    methods: {
        edit(flag) {
            this.isEdit = flag
        },
        getIds() {
            let ids = []
            this.getValetCartData.forEach((pro) => {
                pro.SubItems.forEach((sub) => {
                    ids.push(String(sub.ID))
                })
            })
            let value = ""
            if (ids.length > 0) {
                value = ids.join(",")
            }
            return value
        },
        change(item) {
            console.log(item)
            if (!item.isSelect) {
                this.$set(item, "isSelect", true)
            } else {
                this.$set(item, "isSelect", false)
            }
            this.selectData = [];
            this.carList.forEach(item => {
                if (item.isSelect) {
                    this.selectData.push(item)
                }
            })
            // 计算全选
            this.isSelectAllFn(this.selectData)

        },
        //全选操作
        checkboxChange(e) {
            this.selectData = [];
            let values = e.detail.value
            let isAll = values.length > 0 && values[0] == "all"
            if (isAll) {
                this.carList.forEach(item => {
                    this.$set(item, "isSelect", true)
                    this.selectData.push(item)
                })
            } else {
                this.carList.forEach(item => {
                    this.$set(item, "isSelect", false)
                })
            }
        },
        //全选是否选中
        isSelectAllFn(data) {
            let isSelectAll = data.length > 0 && data.length == this.carList.length
            return isSelectAll
        },
        getTotal() {
            getTempCartTotal(this.getValetCartData, (back) => {
                this.total = {
                    totalNum: back.totalNum,
                    totalPrice: back.totalPrice,
                    class: back.class,
                }
            })
        },
        carlist() {
            let param = {
                priceType: 1,
                isTempCar: true,
                valetUserId: this.valetUserId,
                warehouseId: this.warehouseId,
                isGift: -1,
            }
            GetCarList(param).then((res) => {
                let carList = []
                let carGift = []
                res.Data.forEach((e) => {
                    if (e.IsGift) {
                        carGift.push(e)
                    } else {
                        carList.push(e)
                    }
                })
                this.carList = carList
                this.carGift = carGift
                this.$forceUpdate()
            })
        },
        // 选择客户
        selectClient() {
            let url = "/pages/select/select-customer?selectType=4"
            this.easyGoTo(url)
        },
        editPrcie(item) {
            this.$refs.priceEdit.open();
            this.curEditPriceItem = item
            this.workerPrice = item.WorkerPrice
            this.changePriceMoney = item.V_GradePrice
        },
        keyPostPriceAmount(e) {
            let val = e.target.value.replace(/(^\s*)|(\s*$)/g, "")
            if (!val) {
                this.couponAmount = ""
                return
            }
            var reg = /[^\d.]/g

            // 只能是数字和小数点，不能是其他输入
            val = val.replace(reg, "")
            // // 保证第一位只能是数字，不能是点
            val = val.replace(/^\./g, "")
            // // 小数只能出现1位
            val = val.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".")
            // // 小数点后面保留2位
            // val = val.replace(/^(\-)*(\d+)\.(\d\d).*$/, "$1$2.$3")
            // // 小数点后面保留4位
            val = val.replace(/^(\-)*(\d+)\.(\d{0,4}).*$/, '$1$2.$3')
            this.$nextTick(() => {
                // if (Number(val) < Number(this.workerPrice)) {
                //     val = this.workerPrice
                // }
                this.changePriceMoney = val
                this.$set(this.curEditPriceItem, "V_GradePrice", val)
            })
        },
        priceEditClose() {
            this.$refs.priceEdit.close()
        },
        priceEditConfirm() {
            this.$refs.priceEdit.close()
        },
        addpro() {
            if (this.valetUserId == 0) {
                this.easyToast("请先选择客户")
                return
            }
            this.easyGoTo(
                "/pages/product/index-valet?selectType=4&valetUserId=" +
                this.storeUserId +
                "&valetUserInfo=" +
                encodeURIComponent(JSON.stringify(this.valetUserInfo)) +
                "&warehouseId=" +
                this.warehouseId,
            )
        },
        getListHeight() {
            //获取商品高度 44 60
            getElementHeight(this, ".main", (e) => {
                console.log(e)
                //#ifdef H5
                this.listHeight = e + "px"
                //#endif
                //#ifdef APP
                this.listHeight = e - 134 + "px"
                //#endif
                this.loadOk = true
            })
        },
        save() {
            let params = {
                "relationIds": [
                    {
                        "relationType": 0,
                        "relationId": this.storeUserId
                    }
                ],
                "priceDetails": []
            }
            if (this.selectData.length == 0) {
                this.easyToast("请选择商品")
                return
            }
            if (this.changePriceMoney < this.workerPrice) {
                this.easyToast("修改价格不能低于成本价")
                return
            }
            this.selectData.forEach(item => {
                params.priceDetails.push({
                    productId: item.ProductId,
                    skuId: item.SkuId,
                    unitId: item.UnitId,
                    unitName: item.UnitName,
                    price: item.V_GradePrice,
                    // groupIdx: "",
                })
            })
            uni.showLoading({
                title: "保存中",
            })
            SaveProductPrice(params).then(res => {
                uni.hideLoading()
                if (res.State == 1) {
                    uni.showToast({
                        icon: "none",
                        title: "保存成功",
                        duration: 2000,
                    })
                    setTimeout(() => {
                        this.easyGoTo("/pages/private/index")
                    }, 2000)
                } else {
                    this.easyToast(res.Msg)
                }
            }).catch(err => {
                uni.hideLoading()
            })
        }
    },
}
</script>

<style lang="scss">
.basic-info {
    height: 224rpx;
    background: linear-gradient(180deg, #FFF2F0 0%, #F7F7F7 100%);
    margin-bottom: 24rpx;

    .title {
        padding: 24rpx;
        font-size: 32rpx;
        font-weight: 500;
    }
}

.product-head {
    display: flex;
    padding: 0 24rpx;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24rpx;

    .title {
        font-size: 32rpx;
        font-weight: 500;
    }

    .btn {
        width: 160rpx;
        height: 50rpx;
        font-size: 24rpx;
        border-radius: 13px;
        border: 1px solid #333333;
    }
}

.choose {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 112rpx;
    font-size: 28rpx;
    margin: 0 24rpx;
    color: $color-gray-1;
    background-color: #ffffff;
    border-radius: 20rpx;
    padding: 0 20rpx;
}

.flex-v-c {
    font-size: 28rpx;
}

.flex-main {
    flex: 1;
    display: flex;
    justify-content: flex-end;
    align-items: center;

    .text-show-line-1 {
        width: 75%;
        font-size: 28rpx;
        text-align: right;
    }
}

.action-bar {
    height: 90rpx;
    margin: 0 24rpx;
    background-color: $color-white;
    border-top-left-radius: 16rpx;
    border-top-right-radius: 16rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 24rpx;
    border-bottom: #F0F0F0 solid 1px;

    .total {
        font-size: 28rpx;
        color: #333333;
    }

    .edit {
        font-size: 28rpx;
        color: #333333;
    }
}

.item-radio {
    display: flex;
    align-items: center;
    margin-right: 20rpx;

    .text {
        margin-left: 5px;
    }
}

.main-con {
    background-color: #ffffff;
    border-radius: 8px;
    margin: 0 24rpx;
    overflow-y: scroll;
}

.product-list {
    margin: 0 24rpx;
    padding-bottom: 160rpx;
}

.product-list-item {
    display: flex;
    flex-direction: column;
    padding: 20rpx $app-page-padding;
    background-color: $color-white;

    .product-main {
        display: flex;
        padding-top: 20rpx;

        .product-main-left {
            margin-right: 20rpx;

            .product-item-img {
                width: 160rpx;
                height: 160rpx;
                border-radius: 20rpx;
                overflow: hidden;
            }
        }

        .product-main-right {
            display: flex;
            flex-direction: column;
            justify-content: space-between;

            .name {
                font-size: 28rpx;
                color: #333333;
            }

            .no {
                font-size: 28rpx;
                color: #999999;
            }

            .spec {
                font-size: 28rpx;
                color: #999999;
            }

            .workerPrice {
                font-size: 24rpx;
                color: #999999;
            }

            .price-group {
                display: flex;
                justify-content: space-between;
                align-items: center;

                .price1 {
                    font-size: 28rpx;
                    color: #333333;
                    margin-right: 20rpx;

                    text {
                        font-weight: bold;
                        font-size: 32rpx;
                    }
                }

                .price2 {
                    font-size: 28rpx;
                    color: #333333;

                    text {
                        font-size: 32rpx;
                        font-weight: bold;
                        color: #F1270C;
                    }
                }

                .edit {
                    padding: 5rpx 12rpx;
                    border-radius: 10rpx;
                    color: $app-color-main !important;
                    border: 1rpx solid $app-color-main;
                    margin-left: 24rpx;
                    font-size: 24rpx !important;
                    font-weight: normal !important;
                }
            }
        }
    }
}

.bottom-bar {
    // position: fixed;
    // bottom: 0;
    // left: 0;
    // width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 120rpx;
    padding: 0 30rpx;
    background: #ffffff;
    box-shadow: 0px -2rpx 10rpx 0px rgba(0, 0, 0, 0.1);
    z-index: 9;

    .btn {
        width: 90%;
        height: 80rpx;
        color: $app-color-main;
        border-radius: 45rpx;
        font-size: 32rpx;
        color: #ffffff;
    }
}

.custom-checkbox-box {
    position: relative;

    .checkbox-mark {
        position: absolute;
        z-index: 0;
        opacity: 0;
    }
}

.mescroll-empty {
    box-sizing: border-box;
    width: 100%;
    padding: 80px 25px;
    text-align: center;

    image {
        width: 140px !important;
        height: 98px !important;
        display: block;
        margin: 0 auto;
    }

    view {
        font-size: 26rpx;
        color: gray;
    }

    .btn {
        width: 180rpx;
        margin: 0 auto;
        margin-top: 30rpx;
    }
}

.pop-return-box {
    background: $color-white;
    border-radius: $border-radius-10;
    padding: $app-page-padding;
    width: 600rpx;

    .pop-return-title {
        display: flex;
        justify-content: center;

        // padding: 0;
        // padding-bottom: 10rpx;
        text {
            font-weight: 700;
            font-size: 34rpx;
        }
    }

    .pop-return-li {
        display: flex;
        justify-content: flex-start;
        align-items: center;
        padding: 10rpx;

        input {
            flex: 1;
            height: 80rpx;
            background: #f0f0f0;
            border-radius: 10rpx;
            font-size: 34rpx;
            color: #000;
            padding-left: 20rpx;
        }

        .workerPrice {
            font-size: 34rpx;
        }

        .strong {
            font-weight: bold;
            font-size: 36rpx;
            color: $app-color-main;
        }
    }

    .pop-action {
        border-top: 1rpx solid rgba(0, 0, 0, 0.1);
        margin: 20rpx -24rpx -24rpx -24rpx;
        height: 110rpx;
        display: flex;
        align-items: center;
        justify-content: center;

        view {
            width: 50%;
            text-align: center;
            height: 110rpx;
            line-height: 110rpx;
            font-size: 34rpx;
            font-weight: bold;
            color: $app-color-main;
        }

        &>view:first-child {
            color: $color-gray-1;
            border-right: 1rpx solid rgba(0, 0, 0, 0.1);
        }
    }

    .return-msg {
        margin-bottom: 20rpx;

        .card-group-cell {
            margin-left: 0 !important;
        }
    }

    .img-title {
        display: flex;
        color: $app-color-text-tip;
        margin-bottom: 20rpx;
    }

    .action {
        display: flex;
        flex-direction: row;

        .btn {
            flex: 1;
            border-radius: $border-radius-10;
            height: 70rpx;

            &:first-child {
                margin-left: 0;
            }
        }
    }
}
</style>
